package com.rykj.util;

import android.content.Context;
import android.graphics.Bitmap;
import android.media.MediaMetadataRetriever;
import android.media.ThumbnailUtils;
import android.net.Uri;
import android.widget.ImageView;

import com.bumptech.glide.Glide;
import com.bumptech.glide.request.RequestOptions;
import com.rykj.R;
import com.rykj.util.transformer.CircleTransformation;

import java.io.File;
import java.math.BigDecimal;
import java.util.concurrent.ExecutionException;

import androidx.annotation.DrawableRes;


/**
 * Description:图片加载工具 author: zhangsan on 16/11/21 下午5:35.
 */

public class ImageUtil {
    private static final String TAG = "ImageUtil";

    public static void loadLocalImage(Context context, ImageView imageView, Uri uri) {
        Glide.with(context).load(uri).into(imageView);
    }

    public static void loadLocalImage(Context context, ImageView imageView, String path) {
        Glide.with(context).load(new File(path)).into(imageView);
    }

    public static void loadImage(Context context, ImageView imageView, String url) {
        Glide.with(context).load(url).into(imageView);
    }

    public static void loadImage(Context context, ImageView imageView, String url, @DrawableRes int errorResId) {
        Glide.with(context).load(url).apply(new RequestOptions().error(errorResId)).into(imageView);
    }

    /**
     *
     */
    public static void loadCircleImage(Context context, ImageView imageView, String url) {
        Glide.with(context).load(url).apply(new RequestOptions().error(R.drawable.default_user).transform(new CircleTransformation())).into(imageView);
    }

    /**
     *
     */
    public static void loadCircleImage(Context context, ImageView imageView, String url, @DrawableRes int errorResId) {
        Glide.with(context).load(url).apply(new RequestOptions().error(errorResId).transform(new CircleTransformation())).into(imageView);
    }


    public static void loadImage(Context context, ImageView imageView, String url, @DrawableRes int placeHolder, @DrawableRes int errorResId) {
        Glide.with(context).load(url).apply(new RequestOptions().error(errorResId).placeholder(placeHolder)).into(imageView);
    }
//    /**
//     * 清除图片所有缓存
//     */
//    public static void clearImageAllCache() {
//        clearImageDiskCache();
//    }
//    /**
//     * 清除图片磁盘缓存
//     */
//    public static void clearImageDiskCache() {
//        try {
//            if (Looper.myLooper() == Looper.getMainLooper()) {
//                new Thread(new Runnable() {
//                    @Override
//                    public void run() {
//                        Glide.get(App.getInstance()).clearDiskCache();
//                        EventBus.getDefault().post(C.EventKey.CLEAR_FINISH);
//
//                    }
//                }).start();
//            } else {
//                Glide.get(App.getInstance()).clearDiskCache();
//                EventBus.getDefault().post(C.EventKey.CLEAR_FINISH);
//            }
//        } catch (Exception e) {
//            e.printStackTrace();
//        }
//    }

    /**
     * 获取Glide造成的缓存大小
     * @return CacheSize
     */
    public static String getCacheSize(Context instance) {
        try {
            return getFormatSize(getFolderSize(Glide.getPhotoCacheDir(instance)));
        } catch (Exception e) {
            e.printStackTrace();
        }
        return "";
    }

    /**
     * 获取指定文件夹内所有文件大小的和
     * @param file
     *         file
     * @return size
     */
    public static long getFolderSize(File file) throws Exception {
        long size = 0;
        try {
            File[] fileList = file.listFiles();
            for (File aFileList : fileList) {
                if (aFileList.isDirectory()) {
                    size = size + getFolderSize(aFileList);
                } else {
                    size = size + aFileList.length();
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return size;
    }

    /**
     * 格式化单位
     * @param size
     *         size
     * @return size
     */
    public static String getFormatSize(double size) {

        double kiloByte = size / 1024;
        if (kiloByte < 1) {
            return size + "B";
        }

        double megaByte = kiloByte / 1024;
        if (megaByte < 1) {
            BigDecimal result1 = new BigDecimal(Double.toString(kiloByte));
            return result1.setScale(2, BigDecimal.ROUND_HALF_UP).toPlainString() + "KB";
        }

        double gigaByte = megaByte / 1024;
        if (gigaByte < 1) {
            BigDecimal result2 = new BigDecimal(Double.toString(megaByte));
            return result2.setScale(2, BigDecimal.ROUND_HALF_UP).toPlainString() + "MB";
        }

        double teraBytes = gigaByte / 1024;
        if (teraBytes < 1) {
            BigDecimal result3 = new BigDecimal(Double.toString(gigaByte));
            return result3.setScale(2, BigDecimal.ROUND_HALF_UP).toPlainString() + "GB";
        }
        BigDecimal result4 = new BigDecimal(teraBytes);

        return result4.setScale(2, BigDecimal.ROUND_HALF_UP).toPlainString() + "TB";
    }

    /**
     * @param path
     *         本地视频文件
     */
    public static Bitmap createVideoThumbnail(String path, int width, int height) {
        Bitmap bitmap = null;
        MediaMetadataRetriever retriever = new MediaMetadataRetriever();
        try {
//            if (url.startsWith("http")) {
//                retriever.setDataSource(url, new HashMap<String, String>());
//            } else {
            retriever.setDataSource(path);
//            }
            bitmap = retriever.getFrameAtTime();
        } catch (RuntimeException ex) {
            // Assume this is a corrupt video file.
        } finally {
            try {
                retriever.release();
            } catch (RuntimeException ex) {
                // Ignore failures while cleaning up.
            }
        }
        if (bitmap != null) {
            bitmap = ThumbnailUtils.extractThumbnail(bitmap, width, height, ThumbnailUtils.OPTIONS_RECYCLE_INPUT);
        }
        return bitmap;
    }

    /**
     *
     */
    public static void getImage(final Context applicationContext, final String yourUrl, final Call call) {
        if (call == null) {
            LogX.d(TAG, "call = null");
            return;
        }
        new Thread(new Runnable() {
            @Override
            public void run() {
                try {
                    Bitmap bitmap = Glide.with(applicationContext).asBitmap() //必须
                            .load(yourUrl).apply(new RequestOptions().centerCrop()).submit(500, 500).get();
                    call.success(bitmap);
                } catch (InterruptedException e) {
                    call.fail();
                    e.printStackTrace();
                } catch (ExecutionException e) {
                    call.fail();
                    e.printStackTrace();
                }
            }
        }).start();
    }

    public interface Call {

        void success(Bitmap bitmap);

        void fail();
    }
}
